package com

import com.amazonaws.AmazonClientException
import com.amazonaws.AmazonServiceException
import com.amazonaws.services.s3.transfer.Transfer
import org.slf4j.LoggerFactory
import kotlin.system.exitProcess

object XferMgrProgress {
    // waits for the transfer to complete, catching any exceptions that occur.
    @JvmStatic
    fun waitForCompletion(xfer: Transfer) {
        try {
            xfer.waitForCompletion()
        } catch (e: AmazonServiceException) {
            LoggerFactory.getLogger(javaClass).error("Amazon service error: ", e)
            exitProcess(1)
        } catch (e: AmazonClientException) {
            LoggerFactory.getLogger(javaClass).error("Amazon client error: ", e)
            exitProcess(1)
        } catch (e: InterruptedException) {
            LoggerFactory.getLogger(javaClass).error("Transfer interrupted: ", e)
            exitProcess(1)
        }
    }

    // Prints progress while waiting for the transfer to finish.
    fun showTransferProgress(xfer: Transfer) {
        // print the transfer's human-readable description
        println(xfer.description)
        do {
            try {
                Thread.sleep(100)
            } catch (e: InterruptedException) {
                LoggerFactory.getLogger(javaClass).error(null, e)
                return
            }
            // Note: so_far and total aren't used, they're just for
            // documentation purposes.
            val progress = xfer.progress
            val so_far = progress.bytesTransferred
            val total = progress.totalBytesToTransfer
            val pct = progress.percentTransferred
            print('\r')
            print("$pct%")
        } while (!xfer.isDone)
        // print the final state of the transfer.
        val xfer_state = xfer.state
        println(" ")
        println("upload $xfer_state")
    }
}
